package com.tulele.vtool.task.async;

import com.tulele.vtool.model.*;
import com.tulele.vtool.model.combinedEntity.CurDayNewLookStatisInfo;
import com.tulele.vtool.service.*;
import com.tulele.vtool.utils.DateUtil;
import com.tulele.vtool.utils.RedisCacheUtil;
import com.tulele.vtool.utils.SysConstant;
import com.tulele.vtool.utils.ToolUtil;
import com.tulele.vtool.wechat.service.WeixinService;
import com.tulele.vtool.wechat.service.WeixinServiceDL;
import com.tulele.vtool.wechat.service.WeixinServiceMap;
import com.tulele.vtool.wechat.service.WeixinServiceNew;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Optional;

@Component
@Slf4j
public class LookArticleAsyncTask {

//    @Autowired
//    private WeixinService weixinService;

//    @Autowired
//    private ObjectFactory<WeixinServiceDL> objectFactory;

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private IUserArticleProcessService userArticleProcessService;

    @Autowired
    private INewLookArticleCountInfoService newLookArticleCountInfoService;

    @Autowired
    private ILookArticleInfoService lookArticleInfoService;

//    @Autowired
//    private PlatformSysInfoConfig platformSysInfoConfig;

    @Autowired
    private SysGzhService sysGzhService;

    @Autowired
    private UserGroupGzhService userGroupGzhService;

    @Async
    public Integer lookOtherUserArticle(LookArticleInfo lookArticleInfo, ArticleInfo articleInfo, String lookUserNickName, String viewType,String springProfilesActive) throws Exception {
        return lookOtherUserArticleSyn(lookArticleInfo, articleInfo, lookUserNickName, viewType,springProfilesActive);
    }

    public Integer lookOtherUserArticleSyn(LookArticleInfo lookArticleInfo, ArticleInfo articleInfo, String lookUserNickName, String viewType,String springProfilesActive) throws Exception {

        //文章类别 1-平台文章 2-早晚打卡文章 3-作品案例 4-商学院课程 5-获客海报
        Integer articleCategory;
        if("5".equals(viewType)){
            articleCategory = 5;
        }else if("4".equals(viewType)){
            articleCategory = 4;
        }else if("3".equals(viewType)){
            articleCategory = 3;
        }else if("0".equals(viewType)){
            articleCategory = 0;
        }else{
            articleCategory = 1;
        }

        int lookArticleId;

        log.info("********** Async lookOtherUserArticle"+",[lookArticleInfo]="+lookArticleInfo.toString()+",[articleInfo]="+articleInfo.toString()+",[lookUserNickName]="+lookUserNickName+",[viewType]="+viewType);
        //查询是否已经有了查看记录
        LookArticleInfo lookArticleInfoInDB = lookArticleInfoService.getLookOtherArticleInfo(lookArticleInfo);
        if (lookArticleInfoInDB == null) {

            LookArticleInfo recordLookArticleInfo = new LookArticleInfo();
            recordLookArticleInfo.setUserId(lookArticleInfo.getUserId());
            recordLookArticleInfo.setOtherUserId(lookArticleInfo.getOtherUserId());
            recordLookArticleInfo.setArticleId(lookArticleInfo.getArticleId());
            recordLookArticleInfo.setLookCount(1);
            recordLookArticleInfo.setTodayLookCount(1);
            recordLookArticleInfo.setCreateTime(DateUtil.getCurDate());
            recordLookArticleInfo.setModifyTime(DateUtil.getCurDate());
            recordLookArticleInfo.setArticleCategory(articleCategory);//文章类别 1-平台文章 2-早晚打卡文章 3-作品案例 4-商学院课程

            //不存在，则添加
            lookArticleInfoService.recordLookArticleInfo(recordLookArticleInfo);
            lookArticleId = recordLookArticleInfo.getId();

        } else {

            //存在，则修改
            int lookCount = Optional.ofNullable(lookArticleInfoInDB.getLookCount()).orElse(0);
            int todayLookCount = Optional.ofNullable(lookArticleInfoInDB.getTodayLookCount()).orElse(0);

            LookArticleInfo modifyLookArticleInfo = new LookArticleInfo();
            modifyLookArticleInfo.setId(lookArticleInfoInDB.getId());
            modifyLookArticleInfo.setTodayLookCount(todayLookCount + 1);
            modifyLookArticleInfo.setLookCount(lookCount + 1);
            modifyLookArticleInfo.setModifyTime(DateUtil.getCurDate());
            modifyLookArticleInfo.setArticleCategory(articleCategory);//文章类别 1-平台文章 2-早晚打卡文章 3-作品案例 4-商学院课程

            lookArticleInfoService.modifyLookArticleInfo(modifyLookArticleInfo);
            lookArticleId = lookArticleInfoInDB.getId();

        }

        //记录新的查看次数
        NewLookArticleCountInfo newLookArticleCountInfo = new NewLookArticleCountInfo();
        newLookArticleCountInfo.setUserId(lookArticleInfo.getUserId());
        newLookArticleCountInfo.setOtherUserId(lookArticleInfo.getOtherUserId());

        NewLookArticleCountInfo newLookArticleCountInfoInDB = newLookArticleCountInfoService.getNewLookArticleInfo(newLookArticleCountInfo);
        if (newLookArticleCountInfoInDB != null && newLookArticleCountInfoInDB.getId() != null) {

            NewLookArticleCountInfo updateNewLookArticleCountInfo = new NewLookArticleCountInfo();
            updateNewLookArticleCountInfo.setId(newLookArticleCountInfoInDB.getId());
            updateNewLookArticleCountInfo.setLookCount(newLookArticleCountInfoInDB.getLookCount() + 1);
            updateNewLookArticleCountInfo.setModifyTime(DateUtil.getCurDate());

            newLookArticleCountInfoService.modifyNewLookArticleInfo(updateNewLookArticleCountInfo);

        } else {

            newLookArticleCountInfo.setLookCount(1);
            newLookArticleCountInfo.setModifyTime(DateUtil.getCurDate());
            newLookArticleCountInfo.setCreateTime(DateUtil.getCurDate());

            newLookArticleCountInfoService.recordNewLookArticleInfo(newLookArticleCountInfo);

        }

        //发送微信公众号通知 yl 20200522 添加
        if (!lookArticleInfo.getArticleId().equals(1866675)){
            sendUserArticleBeLookedWxPushMsg(lookArticleInfo.getUserId(), lookArticleInfo.getOtherUserId(), articleInfo, lookUserNickName,springProfilesActive);
        }
        // yl 屏蔽于20200522
       // sendUserArticleBeLookedWxPushMsg(lookArticleInfo.getUserId(), lookArticleInfo.getOtherUserId(), articleInfo, lookUserNickName);
        //修改阅读数
        if ("2".equals(viewType)) {
            userArticleProcessService.modifyArticleOutReadCount(lookArticleInfo.getArticleId());
        } else {
            userArticleProcessService.modifyArticleInReadCount(lookArticleInfo.getArticleId());
        }

        return lookArticleId;
    }

    /**
     * 发送文章被查看的微信公众号通知
     * @param userId   查看用户ID
     * @param otherId  被查看用户ID-也是微信通知的接受者
     * @param articleInfo
     * @param lookUserNickName
     */
    private void sendUserArticleBeLookedWxPushMsg(Integer userId, Integer otherId, ArticleInfo articleInfo, String lookUserNickName,String springProfilesActive) throws Exception {

        //发送微信公众号通知
        String userOpenId = userInfoService.getUserOpenId(otherId);

        //region （公众号做通）20210902
        UserGroupOpenId ugoId= userGroupGzhService.getUserOpenId(springProfilesActive,otherId);
        if(ugoId!=null){
            userOpenId=ugoId.getOpenId();
        }
        //endregion

        if (StringUtils.isNotBlank(userOpenId) && !articleInfo.getArticleTitle().equals("设计案例") && !articleInfo.getArticleTitle().equals("商学院课程") && !articleInfo.getArticleTitle().equals("获客海报")) {

//            WeixinServiceDL weixinService= objectFactory.getObject();
//            weixinService.reSetConfigStorage(springProfilesActive);
            PlatformSysInfo platformSysInfoConfig= sysGzhService.getPlatformSysInfo(springProfilesActive);
            //WxMpServiceImpl weixinService = WeixinServiceNew.getWeixinService(platformSysInfoConfig.getSysGzh());
            WeixinServiceDL weixinService= WeixinServiceMap.getWeixinService(springProfilesActive);

            int notifySwitchStatus = 1;

            WxNotifyMsgSetInfo wxNotifyMsgSetInfo = userInfoService.getUserNotifySetInfo(otherId);
            if (wxNotifyMsgSetInfo != null) {
                notifySwitchStatus = Optional.ofNullable(wxNotifyMsgSetInfo.getNotifySwitchStatus()).orElse(1);
            }

            log.info("[" + otherId + "notifySwitchStatus] = " + notifySwitchStatus);

            //0-关闭提醒 1-立即提醒 2-15分钟内只提醒一次 3-1小时之内只提醒一次 4-3小时之内只提醒一次
            if (notifySwitchStatus == 0) {
                return;
            }

            //夜间勿扰状态 0-关闭（可以接受消息） 1-打开（夜间不接受消息）
            int nightDisturbStatus = 1;
            if (wxNotifyMsgSetInfo != null) {
                nightDisturbStatus = Optional.ofNullable(wxNotifyMsgSetInfo.getNightDisturbStatus()).orElse(1);
            }

            if (ToolUtil.getNightTimePeriodStatus() && nightDisturbStatus == 1) {
                return;
            }

            //如果不是即时推送类型并且上一次推送时间距离现在只有2分钟，则不推送
            Object userLastWxPushTimeObj = redisCacheUtil.getCacheObject("lastWxPushTime" + otherId);
            if (userLastWxPushTimeObj != null) {
                String userLastWxPushTimeStr = (String)userLastWxPushTimeObj;

                int minuteDiff = DateUtil.getTimeDiff(2, userLastWxPushTimeStr);

                if (notifySwitchStatus > 1 && minuteDiff <= 2) {

                    return;

                }

            }

            //如果是即时推送类型，则只有是同一篇文章被查看了，才做2分钟限制
            Object instantLastWxPushTimeObj = redisCacheUtil.getCacheObject(userId + "instantLastWxPushTime" + otherId + "1articleId" + articleInfo.getId());
            if (instantLastWxPushTimeObj != null) {

                String instantLastWxPushTimeStr = (String)instantLastWxPushTimeObj;

                int minuteDiff = DateUtil.getTimeDiff(2, instantLastWxPushTimeStr);

                if (notifySwitchStatus == 1 && minuteDiff <= 2) {

                    return;

                }
            }

            if (notifySwitchStatus == 2) {

                Object lastWxPushTimeObj = redisCacheUtil.getCacheObject("lastWxPushTime" + otherId);
                if (lastWxPushTimeObj != null) {
                    String lastWxPushTimeStr = (String)lastWxPushTimeObj;

                    int minuteDiff = DateUtil.getTimeDiff(2, lastWxPushTimeStr);

                    if (minuteDiff < 15) {

                        return;

                    }
                }
            }

            if (notifySwitchStatus == 3) {

                Object lastWxPushTimeObj = redisCacheUtil.getCacheObject("lastWxPushTime" + otherId);
                if (lastWxPushTimeObj != null) {
                    String lastWxPushTimeStr = (String)lastWxPushTimeObj;

                    int hourDiff = DateUtil.getTimeDiff(3, lastWxPushTimeStr);

                    if (hourDiff < 1) {

                        return;

                    }
                }
            }

            if (notifySwitchStatus == 4) {

                Object lastWxPushTimeObj = redisCacheUtil.getCacheObject("lastWxPushTime" + otherId);
                if (lastWxPushTimeObj != null) {
                    String lastWxPushTimeStr = (String)lastWxPushTimeObj;

                    int hourDiff = DateUtil.getTimeDiff(3, lastWxPushTimeStr);

                    if (hourDiff < 3) {

                        return;

                    }
                }
            }

            //可以发送之后，直接先设置最后推送时间，避免多个人同时查看时，多次推送
            redisCacheUtil.setCacheObject("lastWxPushTime" + otherId, DateUtil.getFormatDate("yyyy-MM-dd HH:mm:ss", DateUtil.getCurDate()), 86400);

            String kefuMsg = String.format(SysConstant.NEW_USER_LOOK_ARTICLE_INFO_PUSH_A_MSG.replace(SysConstant.frontDomain,platformSysInfoConfig.getFrontDomain()), articleInfo.getArticleTitle());
            int vipStatus = Optional.ofNullable(userInfoService.getUserVipStatus(otherId)).orElse(0);
            if (vipStatus == 1) {
                if (lookUserNickName.equals("微信用户")) {// 当用户昵称为[微信用户]时，不发客服消息
                    kefuMsg = "";
                } else {
                    kefuMsg = String.format(SysConstant.NEW_USER_LOOK_ARTICLE_INFO_PUSH_B_MSG.replace(SysConstant.frontDomain,platformSysInfoConfig.getFrontDomain()), lookUserNickName, articleInfo.getArticleTitle());
                }
            }

            if (notifySwitchStatus == 1) {

                redisCacheUtil.setCacheObject(userId + "instantLastWxPushTime" + otherId + "1articleId" + articleInfo.getId(), DateUtil.getFormatDate("yyyy-MM-dd HH:mm:ss", DateUtil.getCurDate()), 86400);

            } else if (notifySwitchStatus == 2 || notifySwitchStatus == 3 || notifySwitchStatus == 4) {

                CurDayNewLookStatisInfo curDayNewLookStatisInfo = newLookArticleCountInfoService.getCurDayNewLookStatisInfo(otherId);
                if (curDayNewLookStatisInfo != null) {

                    int lookUserCount = Optional.ofNullable(curDayNewLookStatisInfo.getLookUserCount()).orElse(0);
                    int lookCount = Optional.ofNullable(curDayNewLookStatisInfo.getLookCount()).orElse(0);

                    if (lookUserCount > 0 && lookCount > 0) {
                        kefuMsg = String.format(SysConstant.NEW_USER_LOOK_ARTICLE_SUMMARY_INFO_PUSH_B_MSG.replace(SysConstant.frontDomain,platformSysInfoConfig.getFrontDomain()), lookUserCount, lookCount);
                    } else {
                        kefuMsg = SysConstant.NEW_USER_LOOK_ARTICLE_SUMMARY_INFO_PUSH_A_MSG.replace(SysConstant.frontDomain,platformSysInfoConfig.getFrontDomain());
                    }
                }
            }

            /*
            //屏蔽于20200607,测试是不是 推送超过了20条 所以
            Integer lookArticleInfoWxMsgPushTimes = processLookArticleInfoWxMsgPushTimes(otherId);
            if (lookArticleInfoWxMsgPushTimes%10 == 0) {
                kefuMsg = SysConstant.WX_USER_WX_MSG_PUSH_BEYONGD_LIMIT_PUSH_MSG.replace("[count]",lookArticleInfoWxMsgPushTimes.toString());
                kefuMsg=kefuMsg.replace(SysConstant.frontDomain,platformSysInfoConfig.getFrontDomain());
            } else {

                String lastWxPushTimeStr = "";
                Object lastWxPushTimeObj = redisCacheUtil.getCacheObject("lastWxPushTime" + otherId);
                if (lastWxPushTimeObj != null) {
                    lastWxPushTimeStr = (String)lastWxPushTimeObj;
                }
                log.info("[" + otherId + "notifySwitchStatus] = " + notifySwitchStatus + " [lastWxPushTimeStr] = " + lastWxPushTimeStr);

            }

            WxMpKefuMessage message=WxMpKefuMessage.TEXT().toUser(userOpenId).content(kefuMsg).build();
            try {
                weixinService.getKefuService().sendKefuMessage(message);
            } catch (WxErrorException e) {
                e.printStackTrace();
            }
            */

            //20200607 改成10条以内才发
            boolean returnfalg=true;
            UserInfo userInfo = userInfoService.getUserBaseInfoByOpenId(userOpenId);
            Integer lookArticleInfoWxMsgPushTimes = processLookArticleInfoWxMsgPushTimes(otherId);
            if (lookArticleInfoWxMsgPushTimes==10) {
                kefuMsg = SysConstant.WX_USER_WX_MSG_PUSH_BEYONGD_LIMIT_PUSH_MSG.replace("[count]",lookArticleInfoWxMsgPushTimes.toString());
                kefuMsg=kefuMsg.replace(SysConstant.frontDomain,platformSysInfoConfig.getFrontDomain());

                if(userInfo.getPhoneModel().equals(SysConstant.IOS)){
                    kefuMsg =ToolUtil.handleMsgmenuidByIOS(kefuMsg);
                }

                WxMpKefuMessage message=WxMpKefuMessage.TEXT().toUser(userOpenId).content(kefuMsg).build();
                try {
                    returnfalg=weixinService.getKefuService().sendKefuMessage(message);
                } catch (WxErrorException e) {
                    returnfalg=false;
                    e.printStackTrace();
                }
            } else if(lookArticleInfoWxMsgPushTimes<10){
                if (kefuMsg.equals("")) {// 当用户昵称为[微信用户]时，不发客服消息
                    returnfalg = true;
                } else {
                    if(userInfo.getPhoneModel().equals(SysConstant.IOS)){
                        kefuMsg =ToolUtil.handleMsgmenuidByIOS(kefuMsg);
                    }
                    WxMpKefuMessage message=WxMpKefuMessage.TEXT().toUser(userOpenId).content(kefuMsg).build();
                    try {
                        returnfalg=weixinService.getKefuService().sendKefuMessage(message);
                    } catch (WxErrorException e) {
                        returnfalg=false;
                        e.printStackTrace();
                    }
                }
            }

            if(!returnfalg){//发送失败时发送模板消息  20210626 hyl

                Object customerFollowup= redisCacheUtil.getCacheObject("CUSTOMER_FOLLOWUP_MSG_PUSH" + otherId);

                if(customerFollowup==null) {//如果没发过,才发

                    WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                            // 接收者openid
                            .toUser(userOpenId)
                            // 模板id
                            .templateId(platformSysInfoConfig.getSysGzh().getCustomerFollowupTempId())//客户跟进提醒
                            // 模板跳转链接
                            .url(platformSysInfoConfig.getCustomerMenuUrl())
                            .build();

                    String firstMsg = String.format("有人看了您的文章《%s》", articleInfo.getArticleTitle());

                    String remarkMsg = "\uD83D\uDC49回复数字【 1 】看看他/她是谁";

                    // 添加模板数据
                    templateMessage.addData(new WxMpTemplateData("first", firstMsg, "#FF00FF"))
                            .addData(new WxMpTemplateData("keyword1", "-", "#A9A9A9"))
                            .addData(new WxMpTemplateData("keyword2", (vipStatus == 1 ? lookUserNickName : "****"), "#A9A9A9"))
                            .addData(new WxMpTemplateData("keyword3", "潜在客户", "#A9A9A9"))
                            .addData(new WxMpTemplateData("remark", remarkMsg, "#FF0000"));

                    try {
                        weixinService.getTemplateMsgService().sendTemplateMsg(templateMessage);
                        redisCacheUtil.setCacheObject("CUSTOMER_FOLLOWUP_MSG_PUSH" + otherId, 1, 1800);//作用：记录发过给这个用户了
                    } catch (WxErrorException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 修改阅读数
     * @param articleId
     * @param viewType
     */
    @Async
    public void modifyArticleReadCount(Integer articleId, String viewType) {

        if ("2".equals(viewType)) {
            userArticleProcessService.modifyArticleOutReadCount(articleId);
        } else {
            userArticleProcessService.modifyArticleInReadCount(articleId);
        }

    }

    /**
     * 处理文章查看推送次数 24小时之内，查看文章推送次数计数，超过10次则不推送
     * @param userId
     */
    private int processLookArticleInfoWxMsgPushTimes(Integer userId) {

        Integer lookArticleWxPushTimes = (Integer)redisCacheUtil.getCacheObject(userId + "lookArticleWxPushTimes");

        if (lookArticleWxPushTimes == null) {
            lookArticleWxPushTimes = 1;
        }

        int finalLookArticleWxPushTimes = lookArticleWxPushTimes + 1;
        redisCacheUtil.setCacheObject(userId + "lookArticleWxPushTimes", finalLookArticleWxPushTimes, 86400);

        return finalLookArticleWxPushTimes;
    }

}
